const robot = require("robotjs");
const ioHook = require("iohook");

const CLICK_MAP = {
    1: 'left',
    2: 'right',
    3: 'middle'
}

module.exports.MouseHandler = {

    flag: 0,
    logTimeStamp: Date.now(),
    posStack: [],

    logPos(callback) {
        this.logTimeStamp = Date.now();
        ioHook.on('mouseclick', event => {
            // console.log(event);
            this.posStack.push({ ...event, timeStamp: Date.now() });
            typeof callback === "function" && callback(event);
        });
    },

    clearPos(callback) {
        this.posStack.length = 0;
        typeof callback === "function" && callback();
    },

    stopPos(callback) {
        ioHook.removeAllListeners('mouseclick', () => { console.log('removeListener') });
        typeof callback === "function" && callback(this.posStack);
    },

    clickPos(pos, callback) {
        robot.moveMouse(pos.x, pos.y);
        robot.mouseClick(CLICK_MAP[pos.button], 0);
        typeof callback === "function" && callback();
    },

    async clickPosStack(posStack, callback) {
        if (Array.isArray(posStack)) {
            const sleep = async ms => new Promise(resolve => setTimeout(resolve, ms));
            console.time('clickStack');
            await posStack.reduce(async (pre, cur) => {
                robot.moveMouse(cur.x, cur.y);
                robot.mouseClick(CLICK_MAP[cur.button], 0);
                await sleep(cur.timeStamp - pre.timeStamp);
                console.timeLog('clickStack',)
                return cur.timeStamp;
            }, posStack[0].timeStamp);
            console.timeEnd('clickStack');
        }
        typeof callback === "function" && callback();
    }

}